package io.renren.modules.finance.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.poi.ExcelStyleHelper;
import io.renren.modules.finance.dao.FinanceOperationDao;
import io.renren.modules.finance.dao.ProjectAccountDao;
import io.renren.modules.finance.entity.ProjectAccountEntity;
import io.renren.modules.finance.service.FinanceOperationService;

import io.renren.modules.finance.service.ProjectAccountService;
import io.renren.modules.finance.vo.FinanceOperationVoEntity;
import io.renren.modules.project.entity.ProjectContractBillEntity;
import io.renren.modules.project.entity.ProjectContractEntity;
import io.renren.modules.project.service.ProjectContractBillService;
import io.renren.modules.project.service.ProjectContractService;
import io.renren.modules.project.vo.ProjectVoEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("FinanceOperationService")
public class FinanceOperationServiceImpl  extends ServiceImpl<FinanceOperationDao, FinanceOperationVoEntity> implements FinanceOperationService {

    //结算 操作
    @Autowired
    private ProjectAccountService projectAccountService;

    //合同
    @Autowired
    private ProjectContractService projectContractService;

    //合同发票
    @Autowired
    private ProjectContractBillService projectContractBillService;

    @Override
    public List<FinanceOperationVoEntity> getFinanceList(Map<String,Object>params){

        Page<FinanceOperationVoEntity> pagenation = new Page<FinanceOperationVoEntity>();
        pagenation.setSize(new Long(this.baseMapper.getContractCount()).intValue()  );
        List<FinanceOperationVoEntity> financeList = this.baseMapper.getFinanceOperationList(pagenation ,params);
        List<String> contractNoList = new ArrayList<>();
        for (FinanceOperationVoEntity voEntity: financeList) {
            contractNoList.add(voEntity.getContractNo());
        }

        List<ProjectAccountEntity> accountList = projectAccountService.selectList(
                new EntityWrapper<ProjectAccountEntity>().in("contract_no",Joiner.on(",").join(contractNoList)
                ));
        List<ProjectContractBillEntity> billList = projectContractBillService.selectList(
                new EntityWrapper<ProjectContractBillEntity>().in("contract_no",Joiner.on(",").join(contractNoList)
                ));


        // 每个合同加入 发票和收款列表
        for (FinanceOperationVoEntity voEntity: financeList) {
            List<ProjectAccountEntity> tempAccoutList = new ArrayList<>();
            List<ProjectContractBillEntity> tempBillList = new ArrayList<>();
            for (ProjectAccountEntity accountEntity: accountList) {
                if (accountEntity.getContractNo().equals(voEntity.getContractNo()))tempAccoutList.add(accountEntity);
            }
            for (ProjectContractBillEntity billEntity: billList) {
                if (billEntity.getContractNo().equals(voEntity.getContractNo()))tempBillList.add(billEntity);
            }
            voEntity.setAccountList(tempAccoutList);
            voEntity.setBillList(tempBillList);
        }

        return financeList;
    }

    @Override
    public PageUtils getFinanceOperationPage(Map<String,Object>params){
        Page<FinanceOperationVoEntity> pagnation = new Query<FinanceOperationVoEntity>(params).getPage();
        pagnation = pagnation.setRecords( baseMapper.getFinanceOperationList(pagnation , params ) );
        return new PageUtils(pagnation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Workbook exportFinanceExcel(Map<String, Object> params) {
        List<FinanceOperationVoEntity> list = this.getFinanceList(params);
        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        int rowIndex = 0;

        //生成一个表格，设置表格名称
        HSSFSheet sheet = workbook.createSheet("sheet1");

        //设置表格列宽度
        sheet.setColumnWidth(0, 40 * 100);
        sheet.setColumnWidth(1, 170 * 100);
        sheet.setColumnWidth(2, 40 * 100);
        sheet.setColumnWidth(3, 40 * 100);
        sheet.setColumnWidth(4, 40 * 100);
        sheet.setColumnWidth(5, 100 * 100);
        sheet.setColumnWidth(6, 130 * 100);
        sheet.setColumnWidth(7, 130 * 100);
        sheet.setColumnWidth(8, 40 * 100);

        String[] fields = new String[]{"合同编号","合同名称","业务负责人","合同创建时间","合同金额","收支明细","收支备注","发票明细"};
        // 字段行
        HSSFRow tRow = sheet.createRow(rowIndex++);
        tRow.setHeight((short) 420);
        HSSFCell tcell;
        int column = 0;
        for (String field: fields) {
            tcell = tRow.createCell(column++);
            tcell.setCellValue(new HSSFRichTextString(field));
            ExcelStyleHelper.setTileCell(workbook,tcell);
        }

        for(FinanceOperationVoEntity voEntity : list) {
            HSSFRow cRow = sheet.createRow(rowIndex++);
            cRow.setHeight((short) 280);
            HSSFCellStyle cstyle = workbook.createCellStyle();
            cRow.setRowStyle(cstyle);
            HSSFCell cell;
            cell = cRow.createCell(0);
            ExcelStyleHelper.setCellLeftTop(cell);
            cell.setCellValue(new HSSFRichTextString(voEntity.getContractNo()));
            cell = cRow.createCell(1);
            ExcelStyleHelper.setCellLeftTop(cell);
            cell.setCellValue(new HSSFRichTextString(voEntity.getContractName()));
            cell = cRow.createCell(2);
            ExcelStyleHelper.setCellLeftTop(cell);
            cell.setCellValue(new HSSFRichTextString(voEntity.getContractBusiness()));
            cell = cRow.createCell(3);
            ExcelStyleHelper.setCellLeftTop(cell);
            cell.setCellValue(new HSSFRichTextString(DateUtils.format(voEntity.getContractCreateTime())));
            cell = cRow.createCell(4);
            ExcelStyleHelper.setCellRightTop(cell);
            cell.setCellValue(new HSSFRichTextString(String.format( "%.2f",voEntity.getContractMoney() )));
            // 收入明细/备注
            StringBuilder payBuf = new StringBuilder();
            StringBuilder remarkBuf = new StringBuilder();
            for(ProjectAccountEntity accountEntity : voEntity.getAccountList()) {
                payBuf.append(DateUtils.format(accountEntity.getAccountAddDateTime()) + " " +
                                accountEntity.getAccountTypeName() + String.format( "%.2f",accountEntity.getAccountNum()) );
                payBuf.append("\r\n");
                remarkBuf.append(accountEntity.getAccountNote());
                remarkBuf.append("\r\n");
            }
            cell = cRow.createCell(5);
            ExcelStyleHelper.setCellLeftTop(cell);
            ExcelStyleHelper.setCellWrap(cell);
            cell.setCellValue(payBuf.toString());

            cell = cRow.createCell(6);
            ExcelStyleHelper.setCellLeftTop(cell);
            ExcelStyleHelper.setCellWrap(cell);
            cell.setCellValue(remarkBuf.toString());

            // 发票明细备注
            StringBuilder buffer = new StringBuilder();
            for(ProjectContractBillEntity billEntity : voEntity.getBillList()) {
                buffer.append(billEntity.getRemark());
                buffer.append("\r\n");
            }
            cell = cRow.createCell(7);
            ExcelStyleHelper.setCellLeftTop(cell);
            ExcelStyleHelper.setCellWrap(cell);
            cell.setCellValue(buffer.toString());

            int max = Math.max(voEntity.getBillList().size(), voEntity.getAccountList().size());
            if (max > 1) {
                cRow.setHeight((short) (280 * max));
            }
        }


        return workbook;
    }
}
